package com.db.user.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.db.core.vo.R;
import com.db.user.entity.User;
import com.db.user.mapper.MenuMapper;
import com.db.user.mapper.RoleMapper;
import com.db.user.mapper.UserMapper;
import com.db.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.db.user.utils.GetJwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author db
 * @since 2023-10-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    public R login(User user){
        if(StringUtils.isEmpty(user))
            return R.fail("未接收到用户信息");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserName,user.getUserName());
        User user1 = userMapper.selectOne(queryWrapper);
        if (StringUtils.isEmpty(user1))
            return  R.fail("当前用户不存在");
        if (SecureUtil.md5(user.getPassword()).equals(user1.getPassword())){
            //用户信息脱敏
            user1.setPassword("");
            List<String> roles = roleMapper.selectRoleNamesByUserId(String.valueOf(user1.getId()));
            user1.setRoles(roles);
            List<String> menus = menuMapper.selectMenuNamesByUserId(String.valueOf(user1.getId()));
            user1.setMenus(menus);
            //返回令牌
            return  R.ok(GetJwtToken.getTokenExpireInHour(user1,1),"success");
        }
        return  R.fail("用户名或密码不正确") ;
    }


}
